package com.flute.datareceiver.mysql.service;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.flute.datareceiver.data.unit.test.HttpPostTestIndex;
import com.flute.tools.data.DataRecord;
import com.flute.tools.data.mysql.ConnectionInformation;
import com.flute.tools.data.mysql.MysqlHandler;

public class DataToXML {

	private static Properties prop = new Properties();

	private static final String HOST = "host";
	private static final String PORT = "port";
	private static final String USER_NAME = "username";
	private static final String PASSWORD = "password";
	private static final String DB_NAME = "dbname";
	private static final Integer PAGE_ROW = 100000;

	public DataToXML() {
		try {
			String path = DataToXML.class.getResource("/").toString();
			path = path.substring(6, path.length());
			prop.load(new FileInputStream(path + "config/datasource.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Iterator<DataRecord> getData(String sql) {
		ConnectionInformation connInfo = new ConnectionInformation();
		connInfo.setHost(prop.getProperty(HOST));
		connInfo.setPort(prop.getProperty(PORT));
		connInfo.setUserName(prop.getProperty(USER_NAME));
		connInfo.setPassword(prop.getProperty(PASSWORD));
		connInfo.setDbName(prop.getProperty(DB_NAME));
		MysqlHandler handler = new MysqlHandler(connInfo, true);
		return handler.iterator(sql);
	}

	public void createXML(String outPath) {
		String sql = "select t.song_id,t.name,t.singername,t.id_singer,t.hot,t.recordOperator from songindex t";
		Iterator<DataRecord> data = this.getData(sql);
		int dataCount = 0;
		int fileCount = 1;
		Document document = null;
		Element songsElement = null;
		while (data.hasNext()) {
			if (dataCount % PAGE_ROW == 0 && document != null) {
				try {
					System.out.println("正在创建第 " + fileCount + " 个XML文件！");
					OutputFormat format = OutputFormat.createPrettyPrint();
					format.setEncoding("UTF-8");
					XMLWriter writer = new XMLWriter(new FileOutputStream(
							outPath + "/data" + fileCount + ".xml"), format);
					writer.write(document);
					writer.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				fileCount++;
			}
			if (dataCount % PAGE_ROW == 0) {
				document = DocumentHelper.createDocument();
				songsElement = document.addElement("songs");
			}
			Element songElement = songsElement.addElement("song");
			DataRecord dataRecord = data.next();
			// 歌曲
			Element songIdElement = songElement.addElement("song_id");
			String songId = dataRecord.getFieldValue("song_id");
			if (this.isEmpty(songId))
				songIdElement.addText(songId);

			Element songNameElement = songElement.addElement("song_name");
			String songName = dataRecord.getFieldValue("name");
			if (this.isEmpty(songName))
				songNameElement.addCDATA(songName);

			// 歌手
			Element singersElement = songElement.addElement("singers");
			Element singerElement = singersElement.addElement("singer");

			Element singerIdElement = singerElement.addElement("singer_id");
			String singerId = dataRecord.getFieldValue("id_singer");
			if (this.isEmpty(singerId))
				singerIdElement.setText(singerId);

			Element singerNameElement = singerElement.addElement("singer_name");
			String singerName = dataRecord.getFieldValue("singername");
			if (this.isEmpty(singerName))
				singerNameElement.addCDATA(singerName);

			// 专辑
			songElement.addElement("albums");
			// 歌词
			songElement.addElement("lyric");
			// 操作
			Element actionElement = songElement.addElement("action");
			actionElement.addText(dataRecord.getFieldValue("recordOperator"));
			// istop
			songElement.addElement("istop");
			// flag
			Element flagElement = songElement.addElement("flag");
			flagElement.setText("10000");
			// 业务量
			Element businessCountElement = songElement
					.addElement("business_count");
			String businessCount = dataRecord.getFieldValue("hot");
			if (this.isEmpty(businessCount))
				businessCountElement.addText(businessCount);

			dataCount++;
		}
	}

	public boolean isEmpty(String str) {
		if (str == null || "".equals(str)) {
			return false;
		}
		return true;
	}

	public static void main(String[] args) throws Exception {
		DataToXML xml = new DataToXML();
		xml.createXML("d:/datasource");
		System.out.println("已完成数据的转换；正在推送XML文件到DataInterface服务器上......");
		new HttpPostTestIndex().startPost();
		System.out.println("数据推送完毕。");
	}
}
